const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const session = require('koa-session');

const app = new Koa()

const router = new Router();

app.keys = ['some secret hurr'];
const CONFIG = {
  key: 'koa:sess', /** (string) cookie key (default is koa:sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 86400000,
  autoCommit: true, /** (boolean) automatically commit headers (default true) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
};


router.post('/api/login', (ctx, next) => {
  if (ctx.request.body) {
    const { data } = ctx.request.body;
    ctx.status = 200;
    ctx.session.userInfo = {user:data.SysUserInfo, token:data.Token};
    ctx.body = {user:data.SysUserInfo, token:data.Token};
    return;
  }
  ctx.status = 401;
  ctx.body = {message: '401 Bad credentials'};
})



// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = !(app.env === 'production')

async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)
  const {
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 3000
  } = nuxt.options.server

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }

  
  // app.use((ctx) => {
  //   ctx.status = 200

  //   if(!/api\//.test(ctx.request.url)){
  //     ctx.respond = false // Bypass Koa's built-in response handling //此处是绕过Koa的内置响应处理
  //   }
  //   ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
  //   nuxt.render(ctx.req, ctx.res)
  // })
  app.use(bodyParser())
  app.use(session(CONFIG, app));
  app.use(router.routes());
  app.use(router.allowedMethods());

  app.use(async (ctx, next) => {
    // 判断访问路径 例如 如果 URL 是 'api/' 则next执行 让koa-router处理，输出数据
    // 如果不是 ，则交由nuxt 的vue-router来处理判断并返回显示页面
    ctx.req.session = ctx.session
    if (/api\//.test(ctx.request.url)) {
      await next()
    } else {
      ctx.status = 200
      return new Promise((resolve, reject) => {
        ctx.res.on('close', resolve)
        ctx.res.on('finish', resolve)
        nuxt.render(ctx.req, ctx.res, promise => {
          // nuxt.render passes a rejected promise into callback on error.
          promise.then(resolve).catch(reject)
        })
      })
    }
  })

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
